package com.wuba.rxjavademo.lyz;

import java.util.Random;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by liyaxing on 2016/4/12.
 */
public class Demo02 {

    public static void main(String[] ss){
        Demo02 demo = new Demo02() ;
        for (int i = 0; i < 10; i++) {
            demo.createObservable().subscribe(new Subscriber<Integer>() {
                @Override
                public void onCompleted() {
                    System.out.println("==onCompleted==");
                }

                @Override
                public void onError(Throwable e) {
                    System.out.println("error : " + e);
                }

                @Override
                public void onNext(Integer integer) {
                    System.out.println("num : " + integer);
                }
            }) ;
        }

    }

    private Observable<Integer> createObservable(){
        return Observable.<Integer>create(subscriber -> {
            if(!subscriber.isUnsubscribed()){
                int count = 0 ;
                for (int i = 0; i < 5; i++) {
                    int num = new Random().nextInt(10) ;
                    if(num > 8){
                        subscriber.onError(new Throwable("num > 8"));
                        break;
                    }else{
                        count++ ;
                        subscriber.onNext(num);
                    }
                }
                if(count >= 5){
                    subscriber.onCompleted();
                }
            }
        });
    }


}
